package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service(timeout = 3000)
public class DubboCartServiceImpl implements DubboCartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public List<Cart> findCartListByUserId(long userId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return cartMapper.selectList(queryWrapper);
    }

    @Override
    public void updateNum(Cart cart) {
        Cart cartTemp=new Cart();
        cartTemp.setNum(cart.getNum());
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        cartMapper.update(cart, queryWrapper);
    }

    @Override
    public void addCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        Cart cartDB=cartMapper.selectOne(queryWrapper);
        if (cartDB==null){
            cartMapper.insert(cart);
        }else {
            int num=cart.getNum()+cartDB.getNum();
            Cart cartTemp=new Cart();
            cartTemp.setId(cartDB.getId());
            cartTemp.setNum(num);
            cartMapper.updateById(cartTemp);
        }
    }

    @Override
    public void deleteCart(Cart cart) {
        cartMapper.delete(new QueryWrapper<>(cart));
    }
}
